import 'package:ycbl/model/my_course_model.dart';
import 'package:ycbl/net/repository/bl_repository.dart';
import 'package:ycbl/utils/user_config.dart';
import 'package:ycbl/widget/provider/base_view_state_model.dart';

/// 我的课程
class MyCourseViewModel extends BaseViewStateModel {

  /// 普通班课
  List<MyCourseEntity> _myNormalCourseList = [];
  /// 一对一
  List<MyCourseEntity> _myOneCourseList = [];

  /// 正在学
  List<MyCourseEntity> _myLearningList = [];
  List<MyCourseEntity> get myLearningList => _myLearningList;
  /// 未开始
  List<MyCourseEntity> _myNotLearnList = [];
  List<MyCourseEntity> get myNotLearnList => _myNotLearnList;
  /// 已完成
  List<MyCourseEntity> _myFinishedList = [];
  List<MyCourseEntity> get myFinishedList => _myFinishedList;

  /// 班课是否请求成功
  bool _isNormalCoursePrepared = false;
  /// 一对一是否请求成功
  bool _isClassCoursePrepared = false;

  /// 获取我的在学课程
  getMyCourseList() {

    setBusy();

    var userId = UserConfig().getUserId();
    _isNormalCoursePrepared = false;
    _isClassCoursePrepared = false;

    // 获取一对一课程
    BLRepository.getMyOneCourse(
      userId, (myCourseList){
        _myOneCourseList = myCourseList;
        _isClassCoursePrepared = true;
        _notifyDataPrepared();
      }, (err){
        setError(err);
      },
    );

    // 获取普通班课
    BLRepository.getMyNormalCourse(
      userId, (myCourseList){
        _myNormalCourseList = myCourseList;
        _isNormalCoursePrepared = true;
        _notifyDataPrepared();
      }, (err){
        setError(err);
      },
    );

  }

  /// 两组数据都获取成功
  _notifyDataPrepared() {
    //有一个失败 就认为失败了
    if(!isError && _isNormalCoursePrepared && _isClassCoursePrepared) {

      if (_myNormalCourseList.isEmpty && _myOneCourseList.isEmpty) {
        setEmpty();
        return;
      }
      _myLearningList = _filterLearning();
      _myNotLearnList = _filterNotLearn();
      _myFinishedList = _filterFinished();
      setIdle();
    }
  }

  /// 过滤正在学
  List<MyCourseEntity> _filterLearning(){
    return _filter('已开课');
  }

  /// 过滤未开始
  List<MyCourseEntity> _filterNotLearn(){
    return _filter('未开始');
  }

  /// 过滤已完成
  List<MyCourseEntity> _filterFinished(){
    return _filter('已结课');
  }

  /// 过滤条件：已结课 已开课 未开始
  List<MyCourseEntity> _filter(String status) {
    List<MyCourseEntity> list = [];
    //一对一
    list.addAll(
        _myOneCourseList.where(
            (course) => course.status == status
        )
    );
    //班课
    list.addAll(
        _myNormalCourseList.where(
            (course) => course.status == status
        )
    );

    return list;
  }
}